//
//  RecommendForYoutController.swift
//  btvideo
//
//  Created by mac on 2020/9/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON
import SwifterSwift
import SwiftyUserDefaults
import RxCocoa
import RxSwift


//推荐特质 瀑布流 -Controller
class ST_RecommendForYouController: UIViewController, ST_PinterestHomeDataAdapterViewDelegate  {
    
    
    
    fileprivate var first = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        //        view.addSubview(matchHeaderView)
        //        matchHeaderView.snp.makeConstraints { (make) in
        //            make.left.right.equalToSuperview()
        //            make.top.equalToSuperview()
        //            make.height.equalTo(matchHeaderView.header_height)
        //        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.refresh_data()
        })
        
        
        binding()
        
    }
    
    
    private func binding(){
        
        self.adapter.delegate = self
        
        self.adapter.searchParam.removeAll()
        
        
        
        SCComponets.location_component.loc_pushed_observer.observe(on: MainScheduler.instance).subscribe(onNext: { v in
            
            if v != nil {
                self.fetch_boot_data()
                print("订阅到 定位更新成功！！-- ST_RecommendForYouController")
            }
        }).disposed(by: rx.disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f != true{
                own.clear_data()
            }else{
                own.report_launched()
            }
            
        }).disposed(by: rx.disposeBag)
    }
    
    func waiting_for_fetch_boot() {
        
        self.play_scan_view()
        
    }
    
    func fetch_boot_data() {
        
        
        self.adapter.searchParam.removeAll()
        
        self.home_filter_model = nil
        
        self.refresh_data()
    }
    
    @objc fileprivate func refresh_data(){
        
        
        self.adapter.reloadData()
        
        self.play_scan_view()
        
    }
    
    private func report_launched(){
        
        JVrequest(PH.reportStartUpApi) { _ in
            
        } failure: { code, err in
            
        }
        
    }
    
    func reload_view_from_data_adapter(currentCount:Int){
        
        
        
        self.stop_scan_view()
        
        if self.playerView.parentViewController == self{
            
            print("第二次刷新测试222")
            self.playerView.clear_data()
            self.playerView.removeFromSuperview()
        }
        
        
        
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
        
        
        self.collectionView.footer_refresh(count: currentCount) {[weak self] in
            
            self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                
                self?.request_data()
            })
        }
        
        self.collectionView.reloadData()
    }
    
    
    func fail_load_data(code: Int, error: String) {
        
        ToastHud(text: error, view: self.view)
        
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
        
    }
    
    @objc func refresh_data_from_remote(){
        
        clear_data()
        request_data()
    }
    
    @objc func clear_data(){
        
        self.adapter.clear_data()
        self.adapter.searchParam.removeAll()
        self.home_filter_model = nil
        
    }
    
    func refresh_header_layout(){
        
        
        if Defaults[.isPanda] {
            layout.header_height = 0
        }else{
            layout.header_height = (ScreenWidth - 10 * 4)/3/112.0*60.0+15
        }
        
        
        layout.invalidateLayout()
        
    }
    
    
    //    MARK: - Filter
    
    fileprivate var home_filter_model: ST_PinterestHomeFilterModel?
    
   
    //    MARK:- properties
    
    fileprivate lazy var adapter = ST_PinterestHomeDataAdapter()
    
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        
        if Defaults[.isPanda] {
            controlLayout.header_height = 0
        }else{
            controlLayout.header_height = (ScreenWidth - 10 * 4)/3/112.0*60.0+15
        }
        
        
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: BTSafeAreaBottom, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_RecommendForYouCell.self)
        control.register(cellWithClass: PinterestGuidanceHomeCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_RecommendForYouHeaderView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 49, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.emptyDataSetSource = self
        
        control.emptyDataSetDelegate = self
        return control
    }()
    
    
    
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    
    
    
    //    MARk: - scan UI
    
    fileprivate func stop_scan_view(){
        
        scan_root_view.isHidden = true
        scan_animate_view.stop()
        
    }
    
    fileprivate func play_scan_view(){
        
        if scan_root_view.superview == nil{
            view.insertSubview(scan_root_view, aboveSubview: collectionView)
            scan_root_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            
            scan_root_view.addSubview(scan_animate_view)
            scan_animate_view.snp.makeConstraints { (make) in
                make.width.height.equalTo(50/375.0*ScreenWidth)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
        }
        scan_root_view.isHidden = false
        scan_animate_view.play()
    }
    
    
    
    fileprivate lazy var scan_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "homeSearchAnimation", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
}


extension ST_RecommendForYouController{
    
    
    @objc func filter_handle()  {
        
        
        let vc = ST_AIRecommendAdvanceFIlterController(filterModel: self.home_filter_model)
        
        vc.refresh_closure = {[weak self] pm in
            
            self?.home_filter_model = pm
            
            self?.adapter.searchParam = pm.conver_to_param()
            
            self?.adapter.reloadData()
            
        }
        
        let home_filter_navigation_controller =  UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
        
        home_filter_navigation_controller.overCurrentContext = true
        
        GlobalPresent(toController: home_filter_navigation_controller)
    }
}



//MARK: - Request Data
extension ST_RecommendForYouController{
    
    fileprivate func request_data(){
        
        if self.adapter.currentPage == 0{
            play_scan_view()
        }
        
        self.adapter.load_data_from_remote()
        
    }
    
}


extension ST_RecommendForYouController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: "没有找到相关用户或特质呢")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_活跃(空)")
    }
}

extension ST_RecommendForYouController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    /*
     func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
     
     if let last = current_play_index_path,last.row == indexPath.row{
     self.pause_video()
     }
     }
     */
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_RecommendForYouHeaderView.self, for: indexPath)
        
        return header
        
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        let a = self.adapter.data_array.count - indexPath.row
        
        
        if a <= 8 {
            
            self.collectionView.mj_footer?.beginRefreshing()
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return self.adapter.data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.adapter.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let m = self.adapter.data_array[indexPath.item]
        
        if m.type.rawValue > 1{
            
            let cell = collectionView.dequeueReusableCell(withClass: PinterestGuidanceHomeCell.self, for: indexPath)
            
            cell.bind_model(m)
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_RecommendForYouCell.self, for: indexPath)
        
        cell.model = m
        
        cell.ignore_somebody_closure = { [weak self] id , str in
            self?.ignore(userId: id, notice: str)
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        /*
         //        查看活跃的人 或者 查看新人
         if let cell = self.collectionView.cellForItem(at: indexPath) as? PinterestGuidanceHomeCell,cell.guidanceType != .normal{
         //             查看活跃的人
         if cell.guidanceType == .active{
         self.navigationController?.pushViewController(PinterestActiveViweController())
         }
         //          查看新人
         else if cell.guidanceType == .join{
         self.navigationController?.pushViewController(ST_PinterestNewGirlsViewController())
         }
         return
         }
         */
        
        
        guard  let item = self.adapter.data_array[safe:indexPath.item] else{return}
        
        //        判断引导
        if item.type.rawValue > 1{
            self.presentOther(item_model: item)
        }else{
            self.present_detail(item: item, indexPath: indexPath)
        }
        
    }
    
    
    
    func scroll_to_top_by_main_btn(){
        
        self.collectionView.setContentOffset(CGPoint.zero, animated: true)
        
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if self.playerView.parentViewController == self{
            print("第二次刷新测试223333332")
            self.playerView.clear_data()
        }
        
        playerView.removeFromSuperview()
        
    }
    
    /*
     fileprivate func pause_video(){
     
     if playerView.superview == nil {
     return
     }
     
     if playerView.frame.width == ScreenWidth{
     return
     }
     
     playerView.clear_data()
     
     playerView.removeFromSuperview()
     }
     */
}


//MARK: - Event
extension ST_RecommendForYouController{
    
    
    
    func ignore(userId:String,notice:String){
        
        IgnoreBehavior(userId: userId) { (f, err) in
            
            if f{
                
                ToastHud(text: notice, view: self.view)
                
                main_thread_execute(afterDelay: 1.6) {
                    
                    self.adapter.delete(itemId: userId)
                    
                }
                
            }else{
                self.toast(text: err)
            }
            
        }
        
        
    }
    
    func refresh_guidance_status(){
        
        
        main_thread_execute {
            
            self.collectionView.visibleCells.forEach { (cell) in
                
                guard let iCell = cell as? PinterestGuidanceHomeCell else{return}
                
                iCell.refresh_guidance_status()
                
            }
        }
    }
    
}

//MARK: - 跳转详情
extension ST_RecommendForYouController:ST_PairsTransitionProtocol{
    
    func presentOther(item_model:ST_PinterestHomeCellModel){
        
        if item_model.type == .Guidance_特质 {
            
            push_to_push_peculiarity_controller(navigationController: self.navigationController)
            
        }else if item_model.type == .Guidance_照片 {
            
            self.navigationController?.pushViewController(ST_MyPhotoViewController())
            
        }else if item_model.type == .Guidance_自我介绍 {
            
            
            let vc = ST_EditMyIntroViewController()
            
            vc.update_value_closure = { m in
                
                JVrequest(PH.modifyUserGeneralInfoApi,parameters:["personal_desc":m],success: { (json) in
                    
                    NotificationCenter.default.post(name: NSNotification.Name.my_pairs_user_info_updated, object: nil)
                    
                }) { (code, err) in
                    
                    ToastHud(text: err, view: self.view)
                }
                
            }
            
            self.navigationController?.pushViewController(vc)
            
        }else if item_model.type == .Guidance_个人资料 {
            
            self.navigationController?.pushViewController(ST_EditMyInfoViewController())
        }
        
    }
    
    func present_detail(item:ST_PinterestHomeCellModel,indexPath:IndexPath) {
        
        guard let currCell = collectionView.cellForItem(at: indexPath) as? ST_RecommendForYouCell else{
            return
        }
        
        playerView.clear_data()
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = item.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
//        return
//
//        playerView.setUp(data_array: item.resourceList)
//
//        //        playerView.rightSignLabel.isHidden = !item.is_new_user
//
//
//
//        let rectInScreen = currCell.convert(currCell.picutreframe_in_content_view(), to: nil)
//
//        playerView.present_start_rect = rectInScreen
//        playerView.present_start_idx = indexPath
//        playerView.fromeController = self
//
//
//        let vc = ST_InteractivePairsCenterController.init(album: item.resourceList, accid: item.accid, sign: item.sign, home_pushed: true, data_adapter: self.adapter)
//
//        self.adapter.currPairsUserId = item.accid
//
//        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
//
//        transition.operationView = self.playerView
//
//        nav.transitioningDelegate = transition
//
//        nav.modalPresentationStyle = .custom
//
//        self.present(nav, animated: true, completion: nil)
        
    }
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
    
}


